﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml.Linq;
using System.Xml;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text.RegularExpressions;
using System.Net;
using System.IO;

namespace ConsumoDeAPI
{
    /// <summary>
    /// Lógica de interacción para MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {

        

        public MainWindow()
        {
            InitializeComponent();


            
            this.Loaded += (s, E) =>
            {


                HttpWebRequest httpR = HttpWebRequest.Create("http://api.wunderground.com/api/3a03267917e14923/conditions/forecast/lang:SP/q/Venezuela/Barquisimeto.xml") as HttpWebRequest;
                httpR.BeginGetResponse((AR) =>
                {
                    WebResponse resp = httpR.EndGetResponse(AR);
                    HttpWebResponse response = (HttpWebResponse)resp;
                    Stream streamResponse = response.GetResponseStream();
                    StreamReader streamRead = new StreamReader(streamResponse);
                    string responseString = streamRead.ReadToEnd();
                    // Close the stream object 
                    streamResponse.Close();
                    streamRead.Close();
                    // Release the HttpWebResponse 
                    response.Close();

                }, httpR);



                ConsumoDeAPI.Model.AirportService As = new Model.AirportService();

               var r =  As.getAirportsByCountry("Venezuela");
         
                // PARA GOOGLE
                //###################################3
                //AIzaSyAa3jPzL-vJTAgqJUN7mG8IHrOJRWNAXEQ
           
               // 014330377402673986199:mxy8xytvagy

                //https://www.googleapis.com/customsearch/v1?key=AIzaSyAa3jPzL-vJTAgqJUN7mG8IHrOJRWNAXEQ&cx=014330377402673986199:mxy8xytvagy&q=Barquisimeto
               // ConsumoDeAPI.Model.ServiceModel sm = new Model.ServiceModel(new Uri("https://www.googleapis.com/customsearch/v1?key=AIzaSyAa3jPzL-vJTAgqJUN7mG8IHrOJRWNAXEQ&cx=014330377402673986199:mxy8xytvagy&q=Barquisimeto&alt=atom"));
                
                //#################################################

                //PARA FLICKER###################################

              //   ConsumoDeAPI.Model.ServiceModel sm = new Model.ServiceModel(new Uri("http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=b604df2b2b5b46f85215b57bfd1e5d83&text=Barquisimeto&sort=relevance&content_type=1&per_page=10&page=1&format=rest&auth_token=72157634211850255-4bee7f453fbc5bd1&api_sig=e97ccb7c58edcf75566449d2279357ea"));
               // ConsumoDeAPI.Model.ServiceModel sm = new Model.ServiceModel(new Uri("http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=3568d77eb147ceb15d80de64e437b83a&text=Barquisimeto&format=rest"));                                                                      
                


                
                //############################################################
                
          


                //PARA WHEATHER##########################################333

                //IMAGEN
                //http://api.wunderground.com/api/3a03267917e14923/animatedsatellite/q/Venezuela/Barquisimeto.gif
                
                //PRONOSTICO
                //  http://api.wunderground.com/api/3a03267917e14923/conditions/forecast/lang:SP/q/Venezuela/Barquisimeto.xml
                 

                 ConsumoDeAPI.Model.ServiceModel sm = new Model.ServiceModel(new Uri("http://api.wunderground.com/api/3a03267917e14923/conditions/forecast/lang:SP/q/Venezuela/Barquisimeto.xml"));
                //###################################################333

               
                
                //########################### PARA BING

                // Noticias
            //https://api.datamarket.azure.com/Bing/Search/v1/News?Query=%27Barquisimeto%27&Market=%27es-ES%27&NewsSortBy=%27Date%27

             // ConsumoDeAPI.Model.ServiceModel sm = new Model.ServiceModel(new Uri("http://www.bing.com"));
                sm.ServiceResponseReady += new EventHandler<Model.ResponseEventArg>(sm_ServiceResponseReady);
                
                
                sm.Request();

              //  sm.traducir();
            
            
            };

        
        }

        const string HTML_TAG_PATTERN = "<.*?>";

        static string StripHTML(string inputString)
        {
            return Regex.Replace
              (inputString, HTML_TAG_PATTERN, string.Empty);
        }

        void sm_ServiceResponseReady(object sender, Model.ResponseEventArg e)
        {
            string r = (e).Result;
            
            //PASEAR NOTICIAS

           // ParseNoticias(r);

          //  ParseFotoUrl(r);

            ParseWeather(r);

           // ParseBingFotos(r);

          //  ParseBingNoticias(r);

        }

private void ParseFotoUrl(string r)
{


            XDocument doc = XDocument.Parse(r);
            var rr = (from ph in doc.Descendants("photo") select new { title = ph.Attribute("title").Value,
                                                                        id = ph.Attribute("id").Value,
                                                                        farm = ph.Attribute("farm").Value,
                                                                        server = ph.Attribute("server").Value,
                                                                        secret = ph.Attribute("secret").Value
            }).ToList();



            this.Dispatcher.Invoke(new System.Action(() =>
            {
                foreach (var item in rr) {
                    resultText.Text += string.Format("http://farm{0}.staticflickr.com/{1}/{2}_{3}_b.jpg", item.farm, item.server, item.id, item.secret) + " \n";
                }
            }), new object[] { });
        
}

private void ParseWeather(string r)
{ 


    XDocument doc = XDocument.Parse(r);


    var actualTime = (from day in doc.Descendants("current_observation")
                      select new {tempC = day.Element("temp_c").Value,
                                  tempF = day.Element("temp_f").Value,
                                  condicion = day.Element("weather").Value,
                                  icon = day.Element("icon").Value,
                                  iconUrl = day.Element("icon_url").Value
                      
                      }).ToList();
      
    
    
    var days = (from day in doc.Descendants("simpleforecast").Descendants("forecastday") 
              select day).ToList();



    var result = (from aux in days
                  select new
                  {
                      Dia = aux.Descendants("weekday").First().Value,
                      AltaC = aux.Descendants("high").First().Element("celsius").Value,
                      AltaF = aux.Descendants("high").First().Element("fahrenheit").Value,
                      BajaC = aux.Descendants("low").First().Element("celsius").Value,
                      BajaF = aux.Descendants("low").First().Element("fahrenheit").Value,
                      Condicion = aux.Descendants("conditions").First().Value,
                      icon = aux.Descendants("icon").First().Value,
                      iconUrl = aux.Descendants("icon_url").First().Value

                  }).ToList();
                              




    this.Dispatcher.Invoke(new System.Action(() =>
    {
        resultText.Text += actualTime[0].ToString() + " \n";

        foreach (var item in result)
        {
            resultText.Text += item.ToString()+ " \n";
        }
    }), new object[] { });

}

  private void ParseNoticias(string r)
     {
            XmlReader reader = XmlReader.Create(new System.IO.StringReader(r));
            System.ServiceModel.Syndication.SyndicationFeed sf = System.ServiceModel.Syndication.SyndicationFeed.Load(reader);


            var news = from noticia in sf.Items
                       //  select new { Titulo =  "<head> <meta http-equiv='Content-Type' content='text/html;charset=UTF-8'> </head> <body scroll='no'>"+ noticia.Title.Text, Resumen = noticia.Summary.Text,Link = noticia.Id };
                       select new { Titulo = StripHTML(noticia.Title.Text), Resumen = StripHTML(noticia.Summary.Text), Link = noticia.Id, imageUrl = noticia.Title };


            this.Dispatcher.Invoke(new System.Action(() =>
            {
                foreach (var item in news)
                {
                    resultText.Text += string.Format("Titulo: <head> <meta http-equiv='Content-Type' content='text/html;charset=UTF-8'> </head> {0}, Resumen:{1}, Link = {2}", item.Titulo, item.Resumen, item.Link) + " \n";
                }

                Noticias.ItemsSource = news;

            }), new object[] { });




        }

  private void ParseBingFotos(string r)  
  {
      XmlReader reader = XmlReader.Create(new System.IO.StringReader(r));
      System.ServiceModel.Syndication.SyndicationFeed sf = System.ServiceModel.Syndication.SyndicationFeed.Load(reader);
      //System.ServiceModel.Syndication.XmlSyndicationContent ttt = sf.Items.First().Content as System.ServiceModel.Syndication.XmlSyndicationContent;

      XDocument xd = XDocument.Parse(r);

      var Xns= XNamespace.Get("http://www.w3.org/2005/Atom");
      var XnsM = XNamespace.Get("http://schemas.microsoft.com/ado/2007/08/dataservices/metadata");
      var XnsD = XNamespace.Get("http://schemas.microsoft.com/ado/2007/08/dataservices");

      var Entries = from ent in xd.Elements().First().Descendants(Xns + "entry")
                    select new { Titulo = ent.Descendants(XnsD + "Title").First().Value, Url = ent.Descendants(XnsD + "MediaUrl").First().Value };

      
      this.Dispatcher.Invoke(new System.Action(() =>
      {
          foreach (var item in Entries)
          {
              resultText.Text += string.Format("Titulo:  {0}, Url: {1}", item.Titulo, item.Url) + " \n";
          }
                   
      }), new object[] { });




  }

  private void ParseBingNoticias(string r) 
  {
      XmlReader reader = XmlReader.Create(new System.IO.StringReader(r));
      XDocument xd = XDocument.Parse(r);
      var Xns = XNamespace.Get("http://www.w3.org/2005/Atom");
      var XnsM = XNamespace.Get("http://schemas.microsoft.com/ado/2007/08/dataservices/metadata");
      var XnsD = XNamespace.Get("http://schemas.microsoft.com/ado/2007/08/dataservices");
         
      
      var Entries = from ent in xd.Elements().First().Descendants(Xns + "entry")
                    select new { Titulo = ent.Descendants(XnsD + "Title").First().Value, Url = ent.Descendants(XnsD + "Url").First().Value,
                                 Fuente = ent.Descendants(XnsD + "Source").First().Value, 
                                 Descripcion = ent.Descendants(XnsD + "Description").First().Value, 
                                 Fecha = ent.Descendants(XnsD + "Date").First().Value };


      this.Dispatcher.Invoke(new System.Action(() =>
      {
          foreach (var item in Entries)
          {
              resultText.Text += string.Format("Titulo:  {0}, Url: {1} , Fuente : {2}, Descripcion : {3}, Fecha: {4} ", item.Titulo, item.Url, item.Fuente, item.Descripcion,item.Fecha) + " \n \n";
          }

      }), new object[] { });

  }

  //private void ParseBingFotos(string r) 
  //{
  //    XmlReader reader = XmlReader.Create(new System.IO.StringReader(r));
  //    XDocument xd = XDocument.Parse(r);
  //    var Xns = XNamespace.Get("http://www.w3.org/2005/Atom");
  //    var XnsM = XNamespace.Get("http://schemas.microsoft.com/ado/2007/08/dataservices/metadata");
  //    var XnsD = XNamespace.Get("http://schemas.microsoft.com/ado/2007/08/dataservices");
        

  //    var Entries = from ent in xd.Elements().First().Descendants(Xns + "entry")
  //                  select new
  //                  {
  //                      Titulo = ent.Descendants(XnsD + "Title").First().Value,
  //                      Url = ent.Descendants(XnsD + "Url").First().Value,
  //                      Fuente = ent.Descendants(XnsD + "Source").First().Value,
  //                      Descripcion = ent.Descendants(XnsD + "Description").First().Value,
  //                      Fecha = ent.Descendants(XnsD + "Date").First().Value
  //                  };


  //    this.Dispatcher.Invoke(new System.Action(() =>
  //    {
  //        foreach (var item in Entries)
  //        {
  //            resultText.Text += string.Format("Titulo:  {0}, Url: {1} , Fuente : {2}, Descripcion : {3}, Fecha: {4} ", item.Titulo, item.Url, item.Fuente, item.Descripcion, item.Fecha) + " \n \n";
  //        }

  //    }), new object[] { });

  //}

  private void Button_Click(object sender, RoutedEventArgs e)
  {
      Model.BingTranslatorService ts = new Model.BingTranslatorService();

      ts.TranslationReadyEvent += (s,r) => {
          Dispatcher.Invoke(new Action<object>((p) => { txtResult.Text = p.ToString(); }), new object[] { r.Result });
      };

      ts.translate(txtFrom.Text, txtTo.Text, txtText.Text);
     
  }

       
    }
}
